import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild, ViewEncapsulation } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ProfileServiceProxy, TaskForModelDto, TaskServiceProxy, OutsourcingWorkFlowInputDto, OutsourcingWorkFlowStepUserDto, UserServiceProxy, OutsourcingFormInputDto, OutsourcingWorkFlowServiceProxy, OutsourcingDto , SupplierServiceProxy, OutsouringServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TaskService } from '../task/Task.service';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { timingSafeEqual } from 'crypto';
import { SelectItem, SelectItemGroup} from 'primeng/api';


@Component({
  selector: 'flowapplyordinarycreate',
  templateUrl: './flowapplyordinarycreate.component.html',
  styleUrls: ['./flowapplyordinarycreate.component.css']

})

// 一般過程外包申請
export class FlowapplyordinarycreateComponent extends AppComponentBase {
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('taskdataTable') taskdataTable: Table;
  @ViewChild('dataTable') dataTable: Table;
  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

  filterText = '';
  active = false;
  saving = false;
  selectedCar3: string;
  task: TaskForModelDto = new TaskForModelDto();
  Outsourcings: OutsourcingDto[];
  workflow: OutsourcingWorkFlowInputDto = new OutsourcingWorkFlowInputDto();

  tasks: TaskForModelDto[];
  SupplierAyy: SelectItem[];

  suppliers: [];
  clonedOutsourcings: { [s: number]: OutsourcingDto; } = {};


  users: SelectItemGroup[];
  stepusers: OutsourcingWorkFlowStepUserDto;

  constructor(injector: Injector,
    private _taskServiceProxy: TaskServiceProxy,
    private _outSourcingworkflowServiceProxy: OutsourcingWorkFlowServiceProxy,
    private _taskService: TaskService,
    private _supplierService: SupplierServiceProxy,
    private _outSourcingServiceProxy: OutsouringServiceProxy,
    private _userService: UserServiceProxy,
    private _profileService: ProfileServiceProxy) {
    super(injector);
  }
  show(taskId?: number): void {
    this.active = true;
    this.filterText = '';
    this.task = new TaskForModelDto();
    this.workflow = new OutsourcingWorkFlowInputDto();
    this._taskService.clearOutSourcs();
    //this.getTasks();
    this._outSourcingworkflowServiceProxy.buildWorkFlowCode().subscribe(flowcode => {
      this.workflow.code = flowcode;
      this.modal.show();
    });
  }

  // tslint:disable-next-line: use-life-cycle-interface
  ngOnInit(): void {
    this._supplierService.getAllSupplierItems().subscribe(resultdata => {
      this.SupplierAyy = resultdata;
    });
    this._userService.getAllUserForDropDown().subscribe(resultdata => {
      console.log(resultdata);
      this.users = resultdata;
    });
   this.stepusers = new OutsourcingWorkFlowStepUserDto();
   this.suppliers = [];
   this.primengTableHelper.records = null;
  }

  onShown(): void {
    //document.getElementById('Code').focus();
  }
  joinTask(task) {
    let outsourcing = this.Outsourcings.filter(x => x.taskForModelId === task.id)[0];

    if (outsourcing === undefined) {
      console.log(outsourcing);
      let _dto = new OutsourcingDto();
      _dto.taskForModelId = task.id;
      _dto.picNo = task.picNo;
      _dto.taskCode = task.code;
      _dto.taskName = task.displayName;
      _dto.taskCount = task.amount;
      _dto.outsouringAmount = 0;
      _dto.deliveryRate = null;
      _dto.workStatus = '';
      _dto.unitPrice = 0;
      this.Outsourcings.push(_dto);
    } else {
      this.notify.info('该任务已经在申请列表中！');
    }

    //this.createOrdinaryForm.show(task);
  }
  save(): void {
    let input = new OutsourcingFormInputDto();
    input.outSourcingDtos = this.Outsourcings;
    this.workflow.supplierUnit = this.suppliers.join(',');
    input.workFlowDto = this.workflow;
    input.stepUserDto = this.stepusers;
    this.saving = true;

    //判断审批用户是否设置
    if (!this.stepusers.workshopManager)
    {
      this.notify.info('请选择单位经办人');
      this.saving = false;
      return ;
    }
    if (!this.stepusers.workShopLeader)
    {
      this.notify.info('请选择单位主管领导');
      this.saving = false;
      return ;
    }
    if (!this.stepusers.plannedProductionModelManager)
    {
      this.notify.info('计划生产处型号主管');
      this.saving = false;
      return ;
    }
    if (!this.stepusers.plannedProductionLeader)
    {
      this.notify.info('计划生产处主管处长');
      this.saving = false;
      return ;
    }
    // tslint:disable-next-line: triple-equals
    if (this.Outsourcings.length == 0)
    {

      this.notify.info('未选择外协任务');
      this.saving = false;
      return ;
    }
    this._outSourcingworkflowServiceProxy.createOrUpdateWorkFlow(input)
      .pipe(finalize(() => { this.saving = false; }))
      .subscribe(() => {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(null);
      });
  }
  close(): void {
    this.active = false;
    this.modal.hide();
  }
  getTasks(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }
    this.primengTableHelper.showLoadingIndicator();
    this._taskServiceProxy.getTaskForModel(
      this.filterText,
      'code',
      this.primengTableHelper.getMaxResultCount(this.paginator, event),
      this.primengTableHelper.getSkipCount(this.paginator, event),
    ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
      this.primengTableHelper.totalRecordsCount = result.totalCount;
      this.primengTableHelper.records = result.items;
      this.primengTableHelper.hideLoadingIndicator();
      this.tasks = result.items;
      _.forEach(this.tasks, viewItem => {
            this._outSourcingServiceProxy.getOutsouringApplyAmountForTaskId(viewItem.id)
                .subscribe(amountresult => {
                    let currentD = this.tasks.find((element) => (element.id === viewItem.id));
                    currentD.outsourcingApplyAmount = amountresult.toString();
                });
        });
    });
  }


  getOutsourcing(event?: LazyLoadEvent) {
    this.Outsourcings = this._taskService.getOutSourcings();
  }

  onRowEditInit(task: OutsourcingDto) {
    console.log(task);
    this.clonedOutsourcings[task.taskForModelId.toString()] = { ...task };
  }

  onRowEditSave(task: OutsourcingDto) {
    if (task.outsouringAmount > 0) {
      delete this.clonedOutsourcings[task.taskForModelId.toString()];
      this.notify.info(this.l('SavedSuccessfully'));
    } else {
      this.notify.info('申请数量不能小于0');
    }
  }

  onRowEditCancel(task: OutsourcingDto, index: number) {
    console.log(this.clonedOutsourcings[task.taskForModelId.toString()]);
    this.Outsourcings[index] = this.clonedOutsourcings[task.taskForModelId.toString()];
    delete this.Outsourcings[task.taskForModelId];
  }
  deleteRow(): void {

  }
}
